package com.gcloud.mesh.framework.core.mq.role;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import javax.annotation.PostConstruct;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.stereotype.Component;

import com.gcloud.mesh.header.vo.RoleVo;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
@ConditionalOnProperty(name = "mesh.mq.enable", havingValue = "true")
public class MyRole {

	@Value("${mesh.mq.role}")
	private String roleType;

	@Value("${mesh.mq.id}")
	private String roleId;

	private static RoleVo role = null;

	@PostConstruct
	public void init() throws Exception {
		role = new RoleVo(roleType, roleId);
		log.info("[MyRole] role type {}, role id {}", roleType, roleId);
	}

	private void initRoleId() {
		// File idFile = new File(bashPath + "my.id");
		File idFile = new File(getCurrentPath(), "my.id");
		if (idFile.exists()) {
			try {
				roleId = FileUtils.readFileToString(idFile);
			} catch (Exception e) {

			}
		}
		if (StringUtils.isBlank(roleId)) {
			String tmp = UUID.randomUUID().toString();
			try {
				FileUtils.writeStringToFile(idFile, tmp, "UTF-8");
				roleId = tmp;
			} catch (IOException e) {

			}
		}
		if (roleId == null) {
			// throw new BaseException("failed to init role id");
			log.info("failed to init role id");
		}
	}

	public String roleType() {
		return roleType;
	}

	public String roleId() {
		return roleId;
	}

	public static RoleVo roleVo() {
		return role;
	}

	private String getCurrentPath() {
		String jarWholePath = MyRole.class.getProtectionDomain().getCodeSource().getLocation().getFile();  
		return jarWholePath;
	}
}
